package org.javaopenaccess.dao;


import org.javaopenaccess.model.InternalSession;

import com.db4o.ObjectContainer;
/**
 * All DAO classes that use Db4o has to extend this class
 * so they are in transaction and can use it.
 * @author Miku
 *
 */
public abstract class AbstractDb4oSupportDao extends AbstractSupportDao{
	private AbstractDb4oTransactionManager txManager;
	
	/**
	 * Constructor, for DAO's that are used
	 * with dynamically changing data sources.
	 * @param session
	 */
	public AbstractDb4oSupportDao(InternalSession session){
		Db4oFileTransactionManager txManager = new Db4oFileTransactionManager();
		this.session = txManager.startTransaction(session, this);
		this.txManager = txManager;
	}
	/**
	 * Default constructor
	 */
	public AbstractDb4oSupportDao(){
		
	}
	
	public void closeTransaction(){
		if (txManager != null){
			txManager.stopTransaction(session, true);
		}else{
			session.close();
		}
	}
	
	private ObjectContainer session;

	public ObjectContainer getSession(){
		if (session != null){
			return session;
		}else {
			throw new TransactionRequiredException("Session is empty in a DAO. Please check the transaction management");
		}
	}

	public void setSession(ObjectContainer session) {
		this.session = session;
	}
}
